package org.tinygroup.ratelimitweblayer;

import java.io.IOException;
import java.util.concurrent.Semaphore;

import javax.servlet.ServletException;

import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.weblayer.AbstractTinyFilter;
import org.tinygroup.weblayer.WebContext;
public class ConnectLimitFilter extends AbstractTinyFilter{
	private final static String CONN_LIMIT = "conn_limit";
	private Semaphore  permit ;
	public void preProcess(WebContext context) throws ServletException,
			IOException {
		if(permit!=null&&!permit.tryAcquire()){
			String characterEncoding = context.getRequest().getCharacterEncoding();
			if(characterEncoding==null){
				characterEncoding="UTF-8";
			}
			context.getResponse().getOutputStream().write("达到流量限制".getBytes(characterEncoding));
		}
	}

	public void postProcess(WebContext context) throws ServletException,
			IOException {
		permit.release();
	}

	protected void customInit() {
		String connLimitValue = get(CONN_LIMIT);
		if(StringUtil.isBlank(connLimitValue)){
			return;
		}
		permit = new Semaphore(Integer.parseInt(connLimitValue)
				);
	}

}
